var map;
var shootLayer; //作业点图层
var jinsheLayer; //禁射区图层
var jinsheAreaLayer;
var checkEidt = false; //表名当前的禁射区是否处于编辑状态
var selectArea;
$(window).load(initMap);

function initMap() {
	map = mapUtil.createMap('map', [97.935, 24.50], 'EPSG:3857', 9, 10, 21);

	var googleLayer=new ol.layer.Tile({
		source:new ol.source.XYZ({
			crossOrigin: 'anonymous',
			url:'http://mt2.google.cn/vt/lyrs=y&hl=zh-CN&gl=cn&x={x}&y={y}&z={z}'
		}),
		zIndex: -1
	});
	map.addLayer(googleLayer);
	getPointsData(); //加载炮点图层
	jinsheLayer = new ol.layer.Vector({
		source: new ol.source.Vector()
	});
	map.addLayer(jinsheLayer);

	jinsheAreaLayer = new ol.layer.Vector({
		source: new ol.source.Vector()
	});
	map.addLayer(jinsheAreaLayer);
	jinsheAreaLayer.setZIndex(9999);
}
//定位一个作业点
function locatShoot(scode) {
	var feas = shootLayer.getSource().getFeatures();
	for (var i = 0; i < feas.length; i++) {
		var shootpoint = feas[i].getProperties().properties;
		if (shootpoint.scode == scode) {
			//找到该作业点
			var coord = ol.proj.transform([shootpoint.lon, shootpoint.lat], 'EPSG:4326', 'EPSG:3857');
			drawJinSheLayer(map, jinsheLayer, shootpoint); //绘制背景
			drawjinsheArea(coord, shootpoint.scode); //绘制安全射区
		}
	}
}

//根据scode获取改作业点的坐标
function getscodeShoot(scode) {
	var feas = shootLayer.getSource().getFeatures();
	for (var i = 0; i < feas.length; i++) {
		var shootpoint = feas[i].getProperties().properties;
		if (shootpoint.scode == scode) {
			//找到该作业点
			//var coord = ol.proj.transform([shootpoint.lon, shootpoint.lat], 'EPSG:4326', 'EPSG:3857');
			//var coord = [shootpoint.lon, shootpoint.lat];
			//return coord;
			return shootpoint;
		}
	}
}
//表单数据设置
function setshootAreaData(result) {
	$('#startR').val("");
	$('#endR').val("");
	$('#startAngle').val("");
	$('#endAngle').val("");
	$('#selectNum').empty();
	$('#selectNum').append("<option value='0'>请选择编号</option>");
	$('#sationName').attr("tag", JSON.stringify(result));
	/* 	var tabledata = []; */
	$.each(result.data, function(i, data) {
		$('#selectNum').append("<option value=" + data.num + ">" + data.num + "</option>");
		/* var dataitem = {
			"num": data.num,
			"az": data.startAz + "°~" + data.endAz + "°",
			"ele": data.startele + "°~" + data.endele + "°"
		};
		tabledata.push(dataitem); */
	});
	initTable(result);
}
//select选中事件
function selectItemChange() {
	var scode = $("#selectNum").find("option:selected").attr('value');
	if (scode == '0') {
		return;
	}
	var areadate = JSON.parse($('#sationName').attr("tag"));
	$.each(areadate.data, function(i, data) {
		if (scode == data.num) {
			$('#startR').val(data.startR);
			$('#endR').val(data.endR);
			$('#startAngle').val(data.startAngle);
			$('#endAngle').val(data.endAngle);
		}
	})
}

function pexport() {
	/* var scode=$("#sationName").attr("value");
	var shootPoint=getscodeShoot(scode);
	shootPoint = ol.proj.transform([shootPoint.lon,shootPoint.lat], 'EPSG:3857', 'EPSG:4326');
	var url = "output.html?scode="+scode+"&lon="+shootPoint[0]+"&lat="+shootPoint[1];//此处拼接内容
	 window.location.href = url; */
	map.once('postcompose', function(event) {
		var canvas = event.context.canvas;
		canvas.toBlob(function(blob) {
			var scode=$("#sationName").attr("value");
			var shootPoint=getscodeShoot(scode);
			var coord=ol.proj.transform([shootPoint.lon,shootPoint.lat], 'EPSG:3857', 'EPSG:4326');
			var maxR=WR1D_dis[WR1D_dis.length-1]*getScale(shootPoint.height); //获取最大的值
			
			saveAs(blob, 'map.png');
		});
	});
	map.renderSync();
}
//增加绘制区按钮
function addArea() {
	//var startR = Number($('#startR').val());
	//var endR = Number($('#endR').val());
	var startAngle = Number($('#startAngle').val());
	var endAngle = Number($('#endAngle').val());
	/* if (endR <= startR) {
		layer.alert('结束半径必须大于开始半径', {icon: 2});
		return;
	}
	if (endAngle <= startAngle) {
		layer.alert('结束角度必须大于开始角度', {icon: 2});
		return;
	} */
	//绘制
	var scode = $("#sationName").attr("value");
	var shootPoint = getscodeShoot(scode);
	var num = $("#selectNum")[0].options.length;

	var startR = WR1D_dis[0] * getScale(shootPoint.height);
	var endR = WR1D_dis[6] * getScale(shootPoint.height);
	var data = {
		"num": num.toString(),
		"startR": startR,
		"endR": endR,
		"startAngle": startAngle,
		"endAngle": endAngle,
	};
	var coord = [shootPoint.lon, shootPoint.lat];
	createAreaFea(jinsheAreaLayer, coord, data); //创建一个安全射区
	//var eleaz=getAZEle(shootPoint.height,startR,endR,startAngle,endAngle); //计算仰角和方位角
	var az = getAZ(startAngle, endAngle);
	data.startAz = az[0];
	data.endAz = az[1];
	data.startele = WR1D_angs[6];
	data.endele = WR1D_angs[0];
	//更新一个编号
	$('#selectNum').append("<option value=" + num.toString() + ">" + num.toString() + "</option>");
	//更新关联数据对象
	var areadata = JSON.parse($('#sationName').attr("tag"));
	areadata.data.push(data);
	$('#sationName').attr("tag", JSON.stringify(areadata));
	$("#selectNum")[0].selectedIndex = num;
	//刷新表格
	initTable(areadata);
	//保存到数据库
}


function saveArea() {
	var num = $("#selectNum").find("option:selected").attr('value').toString();
	if (num == '0' || num == undefined) {
		layer.alert('请选择安全射界区', {
			icon: 0
		});
		return;
	}
	var startAngle = Number($('#startAngle').val());
	var endAngle = Number($('#endAngle').val());
	var scode = $("#sationName").attr("value");
	var shootPoint = getscodeShoot(scode);

	var startR = WR1D_dis[0] * getScale(shootPoint.height);
	var endR = WR1D_dis[6] * getScale(shootPoint.height);
	var data = {
		"num": num.toString(),
		"startR": startR,
		"endR": endR,
		"startAngle": startAngle,
		"endAngle": endAngle,
	};
	var coord = [shootPoint.lon, shootPoint.lat];
	updateAreaFea(num, coord, data);

	var az = getAZ(startAngle, endAngle);
	data.startAz = az[0];
	data.endAz = az[1];
	data.startele = WR1D_angs[6];
	data.endele = WR1D_angs[0];

	//更新关联对象
	var areadata = JSON.parse($('#sationName').attr("tag"));
	for (var i = 0; i < areadata.data.length; i++) {
		if (areadata.data[i].num == num) {
			areadata.data[i] = data;
		}
	}
	//areadata.data.push(areadata.data);
	$('#sationName').attr("tag", JSON.stringify(areadata));
	//刷新表格
	initTable(areadata);
}
//删除按钮事件
function deleteArea() {
	var num = $("#selectNum").find("option:selected").attr('value');
	if (num == '0' || num == undefined) {
		layer.alert('请选择安全射界区', {
			icon: 0
		});
		return;
	}
	//deleteAreaFea(num);
	//更改关联数据
	var areadata = JSON.parse($('#sationName').attr("tag"));
	var index = -1;
	for (var i = 0; i < areadata.data.length; i++) {
		var snum = Number(areadata.data[i].num);
		if (snum > num) {
			areadata.data[i].num = (snum - 1).toString();
		} else if (snum == num) {
			//
			index = i;
		}
	}
	areadata.data.splice(index, 1);
	$('#sationName').attr("tag", JSON.stringify(areadata));
	var scode = $("#sationName").attr("value");
	var shootPoint = getscodeShoot(scode);
	var coord = [shootPoint.lon, shootPoint.lat];
	drawAllArea(coord, areadata);
	//刷新表格
	initTable(areadata);
	$("#selectNum")[0].selectedIndex = index;
	$('#selectNum').change();
}

//获取所有的作业点数据
function getPointsData() {
	$.ajax({
		type: "get",
		url: "data/data.json",
		async: true,
		dataType: 'json',
		cache: false,
		timeout: 30000,
		success: function(result) {
			//处理json数据
			//1.挂载目录
			initTreeData(result);
			//2.加载炮点
			loadPoints(result);
		}
	})
}

function initTreeData(datas) {
	layui.use('tree', function() {
		var tree = layui.tree;
		//渲染
		var cityArray = [];
		$.each(datas, function(i, data) {
			if (cityArray.length > 0) {
				var flag = false;
				for (var i = 0; i < cityArray.length; i++) {
					var scity = cityArray[i].title;
					if (data.city == scity) {
						var shoot = {
							title: data.sname,
							id: data.scode
						};
						cityArray[i].children.push(shoot);
						flag = true;
					}
				}
				if (!flag) {
					var city = {
						title: data.city,
						children: [{
							title: data.sname,
							id: data.scode
						}]
					};
					cityArray.push(city);
				}
			} else {
				var city = {
					title: data.city,
					children: [{
						title: data.sname,
						id: data.scode
					}]
				};
				cityArray.push(city);
			}
		});
		var treeData = [{
			title: '作业点',
			spread: true,
			children: cityArray
		}];
		var inst1 = tree.render({
			elem: '#shoots',
			data: treeData,
			accordion: true,
			click: function(obj) {
				var scode = obj.data.id;
				if (scode) {
					locatShoot(scode);
					//
					$('#sationName').val(obj.data.title);
					$("#sationName").attr("value", scode);
				}

			}
		});
	});
}

function initTable(result) {
	var tabledata = [];
	$.each(result.data, function(i, data) {
		var dataitem = {
			"num": data.num,
			"az": data.startAz + "°~" + data.endAz + "°",
			"ele": data.startele + "°~" + data.endele + "°"
		};
		tabledata.push(dataitem);
	});
	layui.use('table', function() {
		var table = layui.table;
		//展示已知数据
		table.render({
			elem: '#tabledata',
			cols: [
				[ //标题栏
					{
						field: 'num',
						title: '编号',
						width: 60
					},
					{
						field: 'az',
						title: '方位',
						width: 100
					},
					{
						field: 'ele',
						title: '仰角',
						minWidth: 100
					}
				]
			],
			data: tabledata
				//,skin: 'line' //表格风格
				,
			even: true
				//,page: true //是否显示分页
				//,limits: [5, 7, 10]
				,
			limit: 10 //每页默认显示的数量
		});
	});
}
//加载所有的炮点数据到地图上
function loadPoints(datajson) {
	var feas = [];
	$.each(datajson, function(i, pdata) {
		var feature = createPointFeature(pdata);
		feas.push(feature);
	});
	//创建作业点图层
	shootLayer = new ol.layer.Vector({
		source: new ol.source.Vector({
			features: feas
		}),
		style: shootStyle
	});
	map.addLayer(shootLayer); //加载作业点图层到地图
}

function drawJinSheLayer(map, jinsheLayer, shootPObj) {
	jinsheLayer.getSource().clear(); //清空所有的绘制
	var centerP = ol.proj.transform([shootPObj.lon, shootPObj.lat], 'EPSG:4326', 'EPSG:3857');
	shootPObj.lon = centerP[0];
	shootPObj.lat = centerP[1];
	//地图定位
	map.getView().setCenter([shootPObj.lon, shootPObj.lat]);
	map.getView().setZoom(13);

	var angs = [85, 80, 75, 70, 65, 60, 55];
	var dis = [1401, 2126, 3064, 3887, 4591, 5175, 5626];
	var scale = 1.0;
	if (shootPObj.height <= 500) {
		scale = 1.0;
	} else if (shootPObj.height <= 1000) {
		scale = 1.05;
	} else if (shootPObj.height <= 1500) {
		scale = 1.10;
	} else if (shootPObj.height <= 2000) {
		scale = 1.15;
	} else if (shootPObj.height <= 2500) {
		scale = 1.20;
	} else {
		scale = 1.25;
	}
	//计算距离圈半径，并绘制射击距离圈
	for (var i = 0; i < dis.length; i++) {
		// 画一个圆
		var circle = Math.ceil(dis[i] * scale);
		jinsheLayer.getSource().addFeature(drawCircle([shootPObj.lon, shootPObj.lat], circle, 1));
		// 添加标注
		var text = angs[i] + "°";
		var coord = [shootPObj.lon, (shootPObj.lat + circle)];
		drawTextLable(coord, text, 15, -8);
	}

	//绘制水平距离圈
	var maxR = (Math.ceil(dis[6] * scale / 1000)); //向上取整，获取千米最大值
	jinsheLayer.getSource().addFeature(drawCircle([shootPObj.lon, shootPObj.lat], 1000, 0)); //
	jinsheLayer.getSource().addFeature(drawCircle([shootPObj.lon, shootPObj.lat], maxR * 1000, 0));
	//水平距离刻度和标注
	for (var j = 1; j <= maxR; j++) {
		var x = shootPObj.lon + j * 1000;
		var y = shootPObj.lat;
		var coords = [
			[x, y + 50],
			[x, y - 50]
		];
		jinsheLayer.getSource().addFeature(drawKMLine(coords, 0));

		//两个标注
		var text = j + "km";
		if (j == 1) {
			jinsheLayer.getSource().addFeature(drawTextLable([x, y], text, 17, -8));
		} else if (j == maxR) {
			jinsheLayer.getSource().addFeature(drawTextLable([x, y], text, 18, 0));
		}
	}
	//方位线段，每个15°一条射线
	for (var k = 0; k < 24; k++) {
		var jiaodu = (Math.PI * 15 * k) / 180;
		var x1 = maxR * Math.sin(jiaodu) * 1000 + shootPObj.lon;
		var y1 = maxR * Math.cos(jiaodu) * 1000 + shootPObj.lat;
		var coords2 = [
			[shootPObj.lon, shootPObj.lat],
			[x1, y1]
		];
		if (k == 0 || k == 6 || k == 12 || k == 18) {
			jinsheLayer.getSource().addFeature(drawKMLine(coords2, 0));
			//添加标注
			var text = 15 * k + "°";
			if (k == 0) {
				jinsheLayer.getSource().addFeature(drawTextLable([x1, y1], text, 2, -15));
			} else if (k == 6) {
				jinsheLayer.getSource().addFeature(drawTextLable([x1, y1], text, 15, -15));
			} else if (k == 12) {
				jinsheLayer.getSource().addFeature(drawTextLable([x1, y1], text, 5, 15));
			} else {
				jinsheLayer.getSource().addFeature(drawTextLable([x1, y1], text, -18, 0));
			}

		} else {
			jinsheLayer.getSource().addFeature(drawKMLine(coords2, 1));
		}
	}
}

//绘制禁射区
function drawjinsheArea(coord, scode) {
	$.ajax({
		type: "get",
		url: "data/area.json",
		async: true,
		dataType: 'json',
		cache: false,
		timeout: 30000,
		success: function(result) {
			drawAllArea(coord, result);
		}
	})
}
//根据json安全区域数据进行绘制
function drawAllArea(coord, areaDatas) {
	jinsheAreaLayer.getSource().clear(); //清空所有的绘制
	$.each(areaDatas.data, function(i, data) {
		createAreaFea(jinsheAreaLayer, coord, data);
	})
	setshootAreaData(areaDatas);
}
//创建一个新的area
function createAreaFea(jinsheAreaLayer, coord, data) {
	var sector = drawfArea(coord, data);
	var feature = new ol.Feature({
		geometry: sector,
		properties: data
	});
	feature.setStyle(areaStyle(data.num));
	jinsheAreaLayer.getSource().addFeature(feature); // 将圆加入图层
}
//更新一个area
function updateAreaFea(num, coord, data) {
	var feas = jinsheAreaLayer.getSource().getFeatures();
	for (var i = 0; i < feas.length; i++) {
		var area = feas[i].getProperties().properties;
		if (area.num == num) {
			var sector = drawfArea(coord, data);
			feas[i].setGeometry(sector);
			feas[i].getProperties({
				properties: data
			});
			return;
		}
	}
}

//删除一个area
function deleteAreaFea(num) {
	var feas = jinsheAreaLayer.getSource().getFeatures();
	for (var i = 0; i < feas.length; i++) {
		var area = feas[i].getProperties().properties;
		if (area.num == num) {
			jinsheAreaLayer.getSource().removeFeature(feas[i]);
			return;
		}
	}
}

function drawfArea(coord, areaData) {
	var radius1 = areaData.startR;
	var radius2 = areaData.endR;
	var start = areaData.startAngle;
	var end = areaData.endAngle;
	var lobeAngle = 90;
	var antBearing = end - start;
	if (start == 0 && end == 360) {
		antBearing += 1;
	}

	lobeAngle = 360 + lobeAngle - start;
	var polygeo = createRegularPolygonCurve2(coord, radius1, radius2, 100, antBearing, start); //一个扇环
	return polygeo;
}

//创建作业点要素
function createPointFeature(pdata) {
	var centerP = ol.proj.transform([pdata.lon, pdata.lat], 'EPSG:4326', 'EPSG:3857');
	var fea = new ol.Feature({
		geometry: new ol.geom.Point(centerP),
		properties: pdata
	})
	return fea;
}

//作业点图标
function shootStyle(f) {
	//
	var labeltext = f.getProperties().properties.sname ? f.getProperties().properties.sname : "";
	return new ol.style.Style({
		image: new ol.style.Icon({
			src: "img/huojian_lv.png",
			scale: 0.8
		}),
		text: new ol.style.Text({
			text: labeltext,
			offsetX: 0,
			offsetY: -15,
			font: "16px 微软雅黑",
			fill: new ol.style.Fill({
				color: 'white'
			})
		})
	});
}

//实线样式
function shixianStyle() {
	return new ol.style.Style({
		stroke: new ol.style.Stroke({
			color: 'yellow',
			width: 1.2
		})
	});
}

//虚线样式
function xuxianStyle() {
	return new ol.style.Style({
		stroke: new ol.style.Stroke({
			color: 'yellow',
			width: 0.7,
			lineDash: [1, 2, 3]
		})
	});
}

function areaStyle(labeltext) {
	return new ol.style.Style({
		stroke: new ol.style.Stroke({
			color: 'black',
			width: 1.0
		}),
		fill: new ol.style.Fill({
			color: 'rgba(168,233,199,0.5)'
		}),
		text: new ol.style.Text({
			text: labeltext,
			offsetX: 0,
			offsetY: 0,
			font: "18px 微软雅黑",
			fill: new ol.style.Fill({
				color: 'blue'
			})
		})
	});
}
//画一个圆
function drawCircle(center, br, flag) {
	var sector = new ol.geom.Circle(center, br);
	var circlestyle = (flag == 0) ? shixianStyle() : xuxianStyle(); //0为实线，1为虚线
	var feature = new ol.Feature({
		geometry: sector
	});
	feature.setStyle(circlestyle);

	return feature;
	//jinsheLayer.getSource().addFeature(feature); // 将圆加入图层
}

function drawKMLine(coords, flag) {
	var linestyle = (flag == 0) ? shixianStyle() : xuxianStyle(); //0为实线，1为虚线
	var linegeo = new ol.geom.LineString(coords);
	var feature = new ol.Feature({
		geometry: linegeo
	});
	feature.setStyle(linestyle);

	return feature;
	//jinsheLayer.getSource().addFeature(feature); // 将圆加入图层
}

//xt，yt是x方向、y方向平移
function drawTextLable(coord, text, xt, yt) {
	var feature = new ol.Feature({
		geometry: new ol.geom.Point(coord)
	});
	var textStyle = new ol.style.Style({
		text: new ol.style.Text({
			text: text,
			offsetX: xt,
			offsetY: yt,
			font: "14px 宋体",
			fill: new ol.style.Fill({
				color: 'yellow'
			})
		})
	});
	feature.setStyle(textStyle);
	return feature;
	//jinsheLayer.getSource().addFeature(feature);
}


/**
 * @param {Object} origin 圆心
 * @param {Object} radius 半径
 * @param {Object} sides  变数
 * @param {Object} r  弧度
 * @param {Object} angel 方向角
 */
function createRegularPolygonCurve(origin, radius, radius2, sides, r, angel) {
	var rotation = 360 - r;
	var angle = Math.PI * ((1 / sides) - (1 / 2));
	if (rotation) {
		angle += (rotation / 180) * Math.PI;
	}
	var rotatedAngle, x, y;
	var points = [];
	for (var i = 0; i < sides; ++i) {
		var an = i * ((360 - rotation) / 360);
		rotatedAngle = angle + (an * 2 * Math.PI / sides);
		x = origin[0] + (radius * Math.cos(rotatedAngle));
		y = origin[1] + (radius * Math.sin(rotatedAngle));
		points.push([x, y]);
	}

	for (var i = (sides - 1); i >= 0; i--) {
		var an = i * ((360 - rotation) / 360);
		rotatedAngle = angle + (an * 2 * Math.PI / sides);
		x = origin[0] + (radius2 * Math.cos(rotatedAngle));
		y = origin[1] + (radius2 * Math.sin(rotatedAngle));
		points.push([x, y]);
	}

	/* if (rotation != 0) {
		points.push(origin);
	} */
	var ring = new ol.geom.LinearRing(points);
	ring.rotate((-angel / 180) * Math.PI, origin);
	var poy = new ol.geom.Polygon([points]);
	var a = ring.A;
	poy.A = a;

	return poy;
}

function createRegularPolygonCurve2(center, radius, radius2, sides, angle, sAngle) {
	sAngle = (360 - sAngle + 90) % 360;
	var points = [];
	//points.push(center);
	var ep = null;
	var step = angle / sides;
	for (var i = 0; i <= sides; i++) {
		var x = center[0] + radius * Math.cos(degreeToRadian(sAngle + i * step));
		var y = center[1] + radius * Math.sin(degreeToRadian(sAngle + i * step));
		points.push([x, y]);
	}

	for (var i = sides; i >= 0; i--) {
		var x = center[0] + radius2 * Math.cos(degreeToRadian(sAngle + i * step));
		var y = center[1] + radius2 * Math.sin(degreeToRadian(sAngle + i * step));
		points.push([x, y]);
	}
	var ring = new ol.geom.LinearRing(points);
	ring.rotate((-degreeToRadian(angle)), center);
	var poy = new ol.geom.Polygon([points]);
	var a = ring.A;
	poy.A = a;
	return poy;
}
var degreeToRadian = function(degree) {
	return Math.PI * degree / 180;
};
